# zope imports
from zope.interface import implements, Interface
from zope.component import adapts
from zope.app.annotation.interfaces import IAnnotations
from zope.event import notify
from persistent.list import PersistentList

# clickcounter
from iqpp.clickcounting.interfaces import IClickCounting
from iqpp.clickcounting.interfaces import IClickCountable
from iqpp.clickcounting.events import Clicked

KEY = "iqpp.clickcounting"

class SimpleClickCounter:
    """Adapter which counts clicks for clickcountable objects.
    """
    implements(IClickCounting)
    adapts(IClickCountable)

    def __init__(self, context):
        """
        """
        self.context = context
        
        annotations = IAnnotations(context)
        counter = annotations.get(KEY)
        
        if counter is None:
            counter = annotations[KEY] = PersistentList()
            counter.append(0)
            
        self.counter = counter

    def click(self):
        """
        """
        self.countClick()
                
    def countClick(self):
        """
        """
        self.counter[0] += 1
        self.doAfterClick()
        
    def doAfterClick(self):
        """
        """
        notify(Clicked(self.context))
        
    def getClicks(self):
        """
        """
        return self.counter[0]

    def getCounters(self):
        """
        """
        return self.counter
        
    def setClicks(self, amount):
        """
        """
        self.counter[0] = amount
        
    def copyClicksFrom(self, source):
        """
        """
        source = IClickCounting(source)
        self.setClicks(source.getClicks())